﻿using JoyAdmin.Core;
using Furion;
using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging; 
using System; 
using System.Data;
using System.Linq;

namespace JoyAdmin.EntityFramework.Core
{
    [AppDbContext("SqliteConnectionString")]
    public class MultiTenantDbContext : AppDbContext<MultiTenantDbContext, MultiTenantDbContextLocator>
    {
         
        public MultiTenantDbContext(DbContextOptions<MultiTenantDbContext> options) : base(options)
        {
            EnabledEntityStateTracked = false; 
        }
        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
        {
            // 获取当前事件对应上下文
            var dbContext = eventData.Context;

            // 获取所有新增和更新的实体
            var entities = dbContext.ChangeTracker.Entries().Where(u => u.State == EntityState.Added || u.State == EntityState.Modified);
            var authorizationManager = App.GetService<IAuthorizationManager>();
            var logger = App.GetService<ILogger>();
            var userId=0L;  
            var userName = "";
            if (authorizationManager.CheckToken())
            {
                userId = authorizationManager.GetUserId();
                userName = authorizationManager.GetUserName();
            }
            foreach (var entity in entities)
            {
                switch (entity.State)
                {
                    // 新增
                    case EntityState.Added:
                        entity.Property(nameof(SysEntity.UpdatedTime)).IsModified = false;
                        entity.Property(nameof(SysEntity.UpdatedUserId)).IsModified = false;
                        entity.Property(nameof(SysEntity.UpdatedUser)).IsModified = false;
                        entity.Property(nameof(SysEntity.CreatedTime)).CurrentValue = DateTimeOffset.Now;
                        entity.Property(nameof(SysEntity.CreatedUserId)).CurrentValue = userId;
                        entity.Property(nameof(SysEntity.CreatedUser)).CurrentValue = userName;
                        break;
                    // 修改
                    case EntityState.Modified:
                        entity.Property(nameof(SysEntity.CreatedTime)).IsModified =false;
                        entity.Property(nameof(SysEntity.CreatedUserId)).IsModified = false;
                        entity.Property(nameof(SysEntity.CreatedUser)).IsModified = false;

                        entity.Property(nameof(SysEntity.UpdatedTime)).CurrentValue = DateTimeOffset.Now;
                        entity.Property(nameof(SysEntity.UpdatedUserId)).CurrentValue = userId;
                        entity.Property(nameof(SysEntity.UpdatedUser)).CurrentValue = userName;
                        break;
                }
                  
            }
        }
    }
}
